package com.codeduck.zk.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-01-07
 */
@RestController
public class IndexController {

    /**
     * You can now use DiscoveryClient, @LoadBalanced RestTemplate,
     * or @LoadBalanced WebClient.Builder to retrieve services and instances data from Zookeeper,
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/hello")
    public String hello(String name) {
        // 获得服务 `demo-provider` 的一个实例
        ServiceInstance instance;
        if (true) {
            // 获取服务 `demo-provider` 对应的实例列表
            List<ServiceInstance> instances = discoveryClient.getInstances("zk-provider");
            // 选择第一个
            instance = instances.size() > 0 ? instances.get(0) : null;
        } else {
            instance = loadBalancerClient.choose("zk-provider");  // 负载均衡调用一个服务实例
        }
        // 发起调用
        if (instance == null) {
            throw new IllegalStateException("获取不到实例");
        }

        // 如果获取到了远程实例，则调用远程服务的api，将拿到的response返回
        String targetUrl = instance.getUri() + "/echo?name=" + name;
        String response = restTemplate.getForObject(targetUrl, String.class);
        // 返回结果
        return "consumer:" + response;
    }
}
